package com.sunshine.lnuplus.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.WebViewUtils
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_web_view.*
import java.lang.Exception

class WebViewActivity : BaseActivity() {

    private var url: String? = null
    private var toolbarTitle: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)

        getData()
        initView()
    }

    private fun getData() {
        val bundle = intent.extras
        url = bundle?.getString("url")
        toolbarTitle = bundle?.getString("title")
    }

    private fun initView() {
        StatusBarUtils.setStatusBarWithColor(this, color)
        title = "加载也是一种态度..."
        WebViewUtils.initWebView(webview)
        webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, progress: Int){
                if(progress == 100){
                    title = toolbarTitle
                }
            }
        }
        webview.loadUrl(url)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.webview_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.share -> {
                try {
                    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                } catch (e: Exception){
                    Toasty.error(this, "$e 打开浏览器失败~").show()
                }
            }
        }
        return true
    }
}
